import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_oss_aliyun/flutter_oss_aliyun.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:fusion_one/Utils/ossUtils.dart';
import 'package:fusion_one/dtos/patientList.dart';
import 'package:fusion_one/dtos/stage.dart';
import 'package:fusion_one/dtos/userinfo.dart';
import 'package:fusion_one/http/api.dart';
import 'package:fusion_one/redux/actions/tokenAction.dart';
import 'package:fusion_one/redux/actions/userAction.dart';
import 'package:fusion_one/redux/states/index.dart';
import 'package:fusion_one/redux/store/index.dart';
import 'package:fusion_one/view/components/patientDetail.dart';

import '../http/request.dart';

class _viewModel {
  void Function(UserInfo userInfo) SetUserInfo;
  _viewModel({required this.SetUserInfo});
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({
    super.key,
  });
  final String title = 'FusionOne';
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Patient> patients = [];
  Patient? choosePatient;
  List<Stage> stages = [];
  @override
  void initState() {
    super.initState();
    getData();
  }

  Future<void> getData() async {
    // 请求用户信息数据
    var userInfoResult = await DioUtils().get('/api/UsersService/GetUserInfo');
    store.dispatch(
        SetUserInfoAction(UserInfo.fromJson(userInfoResult.resultInfo)));
    // 请求患者列表
    var patientResult = await Api.queryPatientList();
    setState(() {
      patients = patientResult;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: StoreConnector<AppState, _viewModel>(
        converter: (store) {
          return _viewModel(SetUserInfo: (UserInfo userInfo) {
            store.dispatch(SetUserInfoAction(userInfo));
          });
        },
        builder: (context, token) {
          return Flex(direction: Axis.horizontal, children: [
            Container(
                height: double.infinity,
                width: 300,
                decoration: const BoxDecoration(
                  border: Border(
                      right: BorderSide(
                          width: 1, color: Color.fromARGB(115, 97, 97, 97))),
                  color: Color.fromARGB(255, 255, 255, 255),
                ),
                // padding: const EdgeInsets.only(top: 20, bottom: 20),
                child: Column(
                  children: [
                    // 表头
                    Container(
                      margin: const EdgeInsets.only(bottom: 10),
                      child: Container(
                        padding: const EdgeInsets.only(left: 10, right: 10),
                        child: Row(
                          children: const <Widget>[
                            Text(
                              "患者ID",
                              style: TextStyle(fontWeight: FontWeight.bold),
                            ),
                            Expanded(child: Text('')),
                            Text(
                              "患者姓名",
                              style: TextStyle(fontWeight: FontWeight.bold),
                            )
                          ],
                        ),
                      ),
                    ),
                    // 患者列表
                    Expanded(
                        child: ListView(
                            scrollDirection: Axis.vertical,
                            shrinkWrap: true,
                            addAutomaticKeepAlives: true,
                            children: patients
                                .map((e) => tableRow(
                                      patient: e,
                                      activePatient: choosePatient,
                                      click: (e) async {
                                        setState(() {
                                          choosePatient = e;
                                        });
                                        // 请求该患者治疗阶段
                                        var list =
                                            await Api.getStageListByPid(e.id);
                                        setState(() {
                                          stages = list;
                                        });
                                      },
                                    ))
                                .toList()))
                  ],
                )),
            Expanded(
              child: Container(
                color: const Color.fromARGB(255, 255, 255, 255),
                height: double.infinity,
                child: PatientDetail(
                  patient: choosePatient,
                  stages: stages,
                ),
              ),
            )
          ]);
        },
      ),
    );
  }
}

// 左侧列表行
class tableRow extends StatefulWidget {
  Patient patient;
  Patient? activePatient;
  final void Function(Patient p) click;
  tableRow({required this.patient, required this.click, this.activePatient});

  @override
  State<tableRow> createState() => _tableState();
}

class _tableState extends State<tableRow> {
  final Color defaultColor = const Color.fromARGB(255, 255, 255, 255); // 默认背景色
  final Color hoverColor = const Color.fromARGB(255, 234, 234, 234); // 移入背景色
  final Color activeColor = const Color.fromARGB(255, 223, 223, 223); // 选中背景色
  Color color = const Color.fromARGB(255, 255, 255, 255); // 当前背景色
  @override
  Widget build(BuildContext context) {
    return MouseRegion(
        cursor: SystemMouseCursors.click,
        onEnter: (event) {
          setState(() {
            color = hoverColor;
          });
        },
        onExit: ((event) {
          setState(() {
            color = defaultColor;
          });
        }),
        child: Listener(
          onPointerDown: (event) {
            widget.click(widget.patient);
          },
          child: Container(
            height: 40,
            padding: const EdgeInsets.only(left: 10, right: 10),
            decoration: BoxDecoration(
                border: const Border(
                    bottom: BorderSide(
                        width: 1, color: Color.fromARGB(255, 206, 206, 206))),
                color: widget.patient.id == widget.activePatient?.id
                    ? activeColor
                    : color),
            child: Row(
              children: <Widget>[
                Text(widget.patient.id),
                const Expanded(child: Text('')),
                Text(widget.patient.patientName)
              ],
            ),
          ),
        ));
  }
}
